<template>
  <div class="app-container">
    <form-selections :is-active="isActive" :items="formItems" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
    <div class="select_flex">
      <div class="operation_button_box">
        <el-button v-action="'product@developAdd'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="add">新增商品</el-button>
        <el-button v-action="'product@conversion'" size="small" type="primary" @click="officialMerchandise">转为正式商品</el-button>
        <el-button v-action="'product@delDevelop'" size="small" type="danger" @click="dels()">批量删除</el-button>
        <el-button v-action="'product@developmentProductExport'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出商品</el-button>
        <el-button v-action="'product@developImprot'" size="small" type="primary" :loading="exportLoading" @click="productImport">导入</el-button>

      </div>
      <div>
        <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">重置</el-button>
      </div>
    </div>
    <!-- <el-form ref="queryParam" :inline="true" :model="queryParam" label-width="110px">
      <div class="filters-wrap clearfix">
        <div class="filters-area">
          <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
            <el-form-item label="">
              <el-select v-model.trim="queryParam.type" clearable placeholder="中文名称或英文名称或供应商">
                <el-option v-for="(item, index) of issignContract" :key="index" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
            <el-form-item label="">
              <el-input v-model.trim="queryParam.value" placeholder="关键字回车搜索" @keyup.enter.native="handleSearch" />
            </el-form-item>
          </el-col>
          <el-col :xs="22" :sm="10" :md="10" :lg="6" :xl="5">
            <el-form-item label="">
              <product-category v-model="queryParam.category_id" @change="handleSearch" />
            </el-form-item>
          </el-col>
        </div>
      </div>
    </el-form> -->
    <div class="page-grid">

      <egrid v-loading="loading" :screen-heigh="screenHeigh" class="egrid" stripe fit border highlight-current-row element-loading-text="正在努力加载中..." :column-type="['selection']" :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" @selection-change="checkIds" />
      <epagination v-if="tableData" :total="total" :current="queryParam.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" />
    </div>
    <down-modul :form-visible-down.sync="downVisible" :url="downUrl" :options-modul="downModulOptions" :search-param="queryParamObj" />
    <!-- 导入 -->
    <import-dialog url="/products/developImprot" title="导入开发商品" :form-visible.sync="importDialogVisible" @download="downLoad" @handleRefresh="handleRefresh" />
  </div>
</template>

<script>
import formOperate from '@/layout/mixin/formOperate'
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import dicValues from '@/components/dicTransform/index'
import codeItem from '@/components/base/code'
import downModul from '@/components/DownModul/index'
import { action } from '@/directive/permission/index.js' // 权限判断指令
// import { downloadxlsx } from '@/utils/index'
import appText from '@/components/appText/index'
import cacheList from '@/layout/mixin/cacheList'
import { downloadStream } from '@/utils/index'
import importDialog from '@/components/importDialog/index'
export default {
  name: 'DevelopProductManager',
  components: { downModul, importDialog },
  directives: {
    action
  },
  mixins: [formOperate, list, cacheList],
  data() {
    const DICTIONARIES = {
      // 包装方式 ：1-普通商品 2-多箱包装
      auditStatus: [
        {
          code: 1,
          name: '普通商品'
        },
        {
          code: 2,
          name: '多箱包装'
        }
      ],
      // 建档状态 1-未完成 2-已完成
      sourceStatus: [
        {
          code: 1,
          name: '未建档'
        },
        {
          code: 2,
          name: '已建档'
        }
      ]
    }
    return {
      importDialogVisible: false,
      otherHeight: 355,
      isActive: false,
      /** *
       * 定义搜索框
       */
      componentName: 'DevelopProductManager',
      classifyList: [],
      queryParam: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        type: '',
        value: '',
        category_id: '',
        name_ch: '',
        name_en: '',
        supplier_name: ''
      },
      formItems: [
        {
          label: '中文名称',
          key: 'name_ch',
          type: 'input',
          placeholder: '请输入中文名称'
        },
        {
          label: '英文名称',
          key: 'name_en',
          type: 'input',
          placeholder: '请输入英文名称'
        },
        // {
        //   label: '所属供应商',
        //   key: 'supplier_name',
        //   type: 'input',
        //   placeholder: '请输入所属供应商'
        // },
        {
          label: '分类',
          key: 'category_ids',
          type: 'cascader',
          cLabel: 'lable',
          cValue: 'value',
          options: []
        }
      ],
      propsClassify: {
        disabled: 'disabled' // 商品分类只能选择二级
      },
      issignContract: [
        {
          name: '中文名称',
          code: 'name_ch'
        },
        {
          name: '英文名称',
          code: 'name_en'
        },
        {
          name: '所属供应商',
          code: 'supplier_name'
        }
      ],

      columns: [
        {
          label: '中文名称',
          prop: 'name_ch',
          width: '200',
          align: 'center',
          tooltip: false,
          component: codeItem,
          propsHandler: function ({ row, col, column }) {
            return {
              code: row.name_ch ? row.name_ch : '',
              routePath: `/product/dataBase/developProductDetail/${row.id}`
            }
          }
        },
        {
          label: '英文名称',
          prop: 'name_en',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '商品分类',
          prop: 'category_text',
          width: '200',
          align: 'center',
          tooltip: false
        },
        // {
        //   label: '所属供应商',
        //   prop: 'supplier_names',
        //   width: '200',
        //   align: 'center',
        //   tooltip: false,
        //   component: appText,
        //   propsHandler({ row }) {
        //     return { text: row.supplier_names || row.supplier_name }
        //   }
        // },
        {
          label: '采购员',
          prop: 'purchase_name',
          width: '200',
          align: 'center',
          tooltip: false,
          component: appText,
          propsHandler({ row }) {
            return { text: row.purchase_name }
          }
        },
        {
          label: '建档状态',
          prop: 'source_status',
          width: '200',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建人',
          prop: 'creator_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '创建时间',
          prop: 'created_at',
          width: '174',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改人',
          prop: 'update_name',
          width: '112',
          align: 'center',
          tooltip: false
        },
        {
          label: '修改时间',
          prop: 'updated_at',
          width: '174',
          align: 'center',
          tooltip: false
        }
      ],
      columnsSchema: {
        包装方式: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['auditStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        },
        建档状态: {
          propsHandler({ col, row }) {
            return {
              dictionaries: DICTIONARIES['sourceStatus'],
              code: row[col.prop]
            }
          },
          component: dicValues
        }
      },
      downModulOptions: [
        // {
        //   'label': '系统sku',
        //   'key': 'code'
        // },
        {
          'label': '中文名称',
          'key': 'name_ch'
        },
        {
          'label': '英文名称',
          'key': 'name_en'
        },
        // {
        //   'label': '商品类型',
        //   'key': 'type_text'
        // },
        {
          'label': '商品分类',
          'key': 'category_name_new'
        },
        {
          'label': '所属供应商',
          'key': 'supplier_name'
        },
        {
          'label': '采购价(RMB)',
          'key': 'purchase_price_rmb'
        },
        {
          'label': '采购价(USD)',
          'key': 'purchase_price_usd'
        },
        {
          'label': '尺寸',
          'key': 'size'
        },
        {
          'label': '重量',
          'key': 'weight'
        },
        {
          'label': '颜色',
          'key': 'color'
        },
        {
          'label': '材质',
          'key': 'material'
        },
        {
          'label': '计量单位',
          'key': 'unit'
        },
        {
          'label': '箱率',
          'key': 'box_rate'
        },
        {
          'label': '包装方式',
          'key': 'packing_method_text'
        },
        {
          'label': '其他备注',
          'key': 'other_remark'
        }
      ], // 导出弹窗 options
      formVisibleDown: false,
      downVisible: false, // 导出 visible
      downUrl: '/products/developmentProductExport', // 导出 url
      exportLoading: false,
      cachePaths: [
        '/product/dataBase/addDevelopProduct',
        '/product/dataBase/developProductDetail'
      ]
    }
  },
  computed: {
    queryParamObj({ issignContract }) {
      const vm = this
      const item = issignContract.find((e) => e.code === vm.queryParam.type)
      const params = {}
      if (item) {
        params[item.code] = vm.queryParam.value
      }
      return params
    }
  },
  created() {
    this.getTreeList()
    this.query()
  },
  mounted() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js）

  },
  activated() {
    this.query()
  },
  methods: {
    // 下载
    downLoad() {
      const vm = this
      vm.$http
        .get('/products/templateDevelop', { responseType: 'blob' })
        .then((res) => {
          downloadStream(res, '开发商品导入模板.xlsx')
        })
    },
    // 导入
    productImport() {
      const vm = this
      vm.importDialogVisible = true
    },
    beforeSearch() {
      const vm = this
      if (vm.queryParam.category_ids && vm.queryParam.category_ids.length > 0) {
        // vm.queryParam.category_id = vm.queryParam.category_ids.pop()
        const arr = vm.queryParam.category_ids
        vm.queryParam.category_id = arr[arr.length - 1]
      } else {
        vm.queryParam.category_id = ''
      }
    },
    handleSearch() {
      const vm = this
      vm.queryParam.page = 1
      vm.query()
    },
    handleRefresh() {
      const vm = this
      vm.queryParam.page = 1
      vm.queryParam.limit = 10
      vm.queryParam.type = ''
      vm.queryParam.value = ''
      vm.queryParam.category_id = ''
      vm.queryParam.category_ids = []
      vm.queryParam.name_ch = ''
      vm.queryParam.name_en = ''
      vm.queryParam.supplier_name = ''
      vm.query()
    },
    handleExport() {
      const vm = this
      vm.downVisible = true
      // vm.exportLoading = true
      // const url = '/products/developmentProductExport'
      // const { type, value, category_id } = vm.queryParam
      // const params = {
      //   category_id
      // }
      // if (type) {
      //   params[type] = value
      // }
      // vm.$http.post(url, params).then(res => {
      //   downloadxlsx(res.data)
      //   vm.exportLoading = false
      // }).catch(() => {
      //   vm.exportLoading = false
      // })
    },
    // 获取商品分类
    getTreeList() {
      const vm = this
      vm.$http.get(`/getListTree`).then(res => {
        const filter = (arr, parentIds = []) => {
          return arr.map(e => {
            e['value'] = e.id
            e['label'] = e.name
            // ids 用于 后续的 级联回填
            const ids = parentIds.concat()
            ids.push(e.id)
            e['ids'] = ids
            if (e.children) {
              e.children = filter(e.children, ids.concat())
            }
            return e
          })
        }
        const data = res.data.filter(e => e.children && e.children.length > 0)
        vm.classifyList = filter(data)
        vm.formItems = vm.formItems.map((arr) => {
          if (arr.key === 'category_ids') {
            arr.options = vm.classifyList
          }
          return arr
        })
        // vm.formItems[0].options = vm.classifyList
        vm.children = vm.classifyList.reduce((list, e) => {
          list = list.concat(e.children)
          return list
        }, [])
      })
    },
    officialMerchandise() {
      if (this.ids.length !== 1) {
        this.$message.error('至多选择一行数据')
        return
      }
      const ids = this.tableData
        .filter((e) => this.ids.includes(e.id))
        .filter((e) => e.source_status === 1)
      if (ids.length !== this.ids.length) {
        return this.$message.error('所选的数据必须是未建档的商品')
      }
      const item = this.tableData.find(e => e.id === this.ids[0])

      this.$confirm(`确定转为正式商品？${item.supplier_id ? '' : '（请在供应链-供应商模块添加供应商信息）'}`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post('products/conversion', { ids: this.ids })
          .then((res) => {
            this.loading = false
            if (res) {
              this.$message.success('转为正式商品成功')
              this.query()
            }
          })
      })
    },
    // 点击搜索
    query() {
      const vm = this
      if (this.beforeSearch !== undefined) {
        this.beforeSearch()
      }
      let url = '/products/developList'
      const { page, limit, type, value, category_id, name_ch, name_en, supplier_name } = vm.queryParam
      url += `?page=${page}&limit=${limit}&category_id=${category_id}&name_ch=${name_ch}&name_en=${name_en}&supplier_name=${supplier_name}`
      if (type) {
        url += `&${type}=${value}`
      }
      this.initTableData(url, '', (data) => {
        this.tableData = data.map(e => {
          if (e.parent_name) {
            e['category_text'] = `${e.parent_name}-${e.category_name}`
          } else {
            e['category_text'] = `${e.category_name}`
          }
          return e
        })
      })
    },
    handleSizeChange(val) {
      this.queryParam.limit = val
      this.query()
    },
    handleCurrentChange(val) {
      this.queryParam.page = val
      this.query()
    },
    // 新增
    add() {
      this.$router.push('/product/dataBase/addDevelopProduct')
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({ row }) {
          return {
            row: row,
            edit: row.source_status !== 2,
            del: row.source_status !== 2,
            editAction: 'product@developEdit',
            delAction: 'product@delDevelop'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          deleteTableClick(row) {
            that.dels(row.id)
          },
          editTableClick(row) {
            that.$router.push({
              path: '/product/dataBase/addDevelopProduct',
              query: { title: '编辑开发商品', id: row.id }
            })
          }
        }
      })
    },
    // 删除
    dels(id) {
      const vm = this
      let ids
      if (id) {
        ids = id.toString()
      } else {
        const length = vm.checkedList.length
        if (length <= 0) {
          return vm.$message.error('至少选择一条数据')
        } else {
          const isEvery = vm.checkedList.every((e) => e.source_status === 1)
          if (!isEvery) {
            return vm.$message.error('已建档的数据不能删除')
          } else {
            ids = vm.checkedList.map((e) => e.id).join(',')
          }
        }
      }
      vm.$confirm(`确定删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        vm.$http.post('/products/delDevelop', { ids }).then(() => {
          vm.query()
        })
      })
    }
  }
}
</script>

<style>
</style>
